import {createStore} from 'vuex'
import {ElMessage} from 'element-plus'
import http from '@/utils/http'
import router from '@/router'
let stAuthorization=localStorage.getItem("Authorization")
const store=createStore({
    state(){
        return {
            Authorization:stAuthorization,//初始化
            userInfo:null
        }
    },
    getters:{
        isLogin(state){
            return !!state.Authorization;
        }
    },
    mutations:{
        login(state,payload){//payload是用信息对象
            state.Authorization=payload.Authorization; //Authorization
            state.userInfo=payload;
            localStorage.setItem("Authorization",payload.Authorization);
            localStorage.setItem("userInfo",JSON.stringify(payload));
        },
        logOut(state){
            state.Authorization=null;
            localStorage.clear();
            router.push("/login")
        }
    },
    actions:{
        async doLogin(context,payload){//context上下文
            let result=await http.get("/user/login",{
                params:payload
            });
            if(result.data.status==200){
                context.commit("login",result.data.data);
                ElMessage({
                    type:"success",
                    message:"登录成功"
                });
                router.push("/manage");
            }else{
                ElMessage({
                    type:"error",
                    message:"账号密码错误"
                })
            }
        }
    }
});
export default store;